<!--
 * @FilePath: Index.vue
 * @Author: jack
 * @Date: 2025-03-06 11:05:01
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-09-22 11:47:15
 * Copyright: 2025 xxxTech CO.,LTD. All Rights Reserved.
 * @Descripttion: 
-->
<template>
    <div class="user-info-box">
        <SearchComp @clear="clearHandle">
            <RowItem label="所属分类" :count="1">
                <el-select v-model="type" filterable style="width:100%;" @change="Search" placeholder="请选择所属分类" :teleported="false">
                    <el-option v-for="(item, index) in typeList" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </RowItem>
            <RowItem label="图片名称" :count="1">
                <el-input clearable placeholder="请输入图片名称搜索" v-model="personQuery.search" prefix-icon="Search"
                    class="input-with-select" @input="Search">
                </el-input>
            </RowItem>
        </SearchComp>
        <div class="xtx-carousel" ref="contentRef">
            <el-button type="primary" @click="Add">添加图片</el-button>
            <el-button type="primary" class="white-bg-btn" plain style="margin-left: 7px;" @click="BatchAdd" :loading="loading">{{ loading ?
                '正在上传,请稍等...' : '批量上传' }}</el-button>
            <el-upload class="uploaderBox" ref="uploaderRef" multiple style="height: 1px;width: 0px;"
                :show-file-list="false" :http-request="uploadAvatorAdd" :before-upload="beforeAvatarUpload">
            </el-upload>
            <div class="listBox" v-if="total != 0">
                <div class="listItem" v-for="(item, index) in sliders" :key="index" @mouseenter="mouserIndex = index"
                    @mouseleave="mouserIndex = -1">
                    <div class="img-view-box">
                        <img :src="item.addr" alt="" />
                    </div>
                    <div class="teacher-name-box">
                        <div class="ellipsis">{{ item.name }}</div>
                    </div>
                    <transition name="fade" mode="out-in">
                        <div class="model-img-box" v-if="mouserIndex == index">
                            <div class="mine-flex-box">
                                <el-icon @click.stop="editItem(item)">
                                    <Edit />
                                </el-icon>
                                <span></span>
                                <el-icon @click.stop="showImage(item,index)">
                                    <View />
                                </el-icon>
                                <span></span>
                                <el-icon @click.stop="delItem(item)">
                                    <Delete />
                                </el-icon>
                            </div>
                        </div>
                    </transition>
                </div>
            </div>
            <el-empty style="margin-top: 80px;" v-if="total == 0" description="暂无数据" />
        </div>
        <Pagination :total="total" align="center" @sizeChange="sizeChange"
        @CurrentChange="CurrentChange" >
        </Pagination>
        <!-- 添加和编辑信息 -->
        <EdtiArticle ref="editRef" :editFormVisible="editFormVisible" :type="type" :typeList="typeList"
            @getList="getList" @modelCancel="modelCancel"></EdtiArticle>
         <!-- 查看图片 -->
         <el-image-viewer v-if="showViewer" @close="closeViewer" :url-list="srcList" :infinite="false"></el-image-viewer>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h, nextTick } from "vue";
import { ElMessage, ElMessageBox, UploadProps, UploadRequestOptions } from 'element-plus'
import EdtiArticle from './EdtiArticle.vue'
import { photosList, xiaobaoList, keyanList, delPhotos,delXiaobao,delKeyan, addPhotos,addXiaobao,addKeyan } from '../../Api/Publish'
import $util from '../../../util/util'
import { getOSS, getSignApi,batchUploadImg } from '../../Api/Upload'
import { PiniaStore } from '../../../store'
const store = PiniaStore()
const loading = ref<boolean>(false)
const mouserIndex = ref<number>(-1)
const editFormVisible = ref<boolean>(false)
const type = ref<string>('1')
const typeList = ref<any>([
    {
        value: '1',
        label: '校园风景'
    },
    // {
    //     value: '2',
    //     label: '学校校报'
    // },
    {
        value: '3',
        label: '科研报'
    }
])
const personQuery = reactive({
    search: '',
    page: 1,
    page_size: 20,
})
const total = ref<Number>(1)
const sliders = ref<any>([])
// 获取权限列表
const getList = async () => {
    const res: any = Number(type.value) === 1 ? await photosList(personQuery) : Number(type.value) === 2 ? await xiaobaoList(personQuery) : await keyanList(personQuery)
    if (res.code !== 1) {
        return ElMessage.error(res.msg)
    }
    sliders.value = res.data.list
    total.value = res.data.total
}
const Search = async () => {
    personQuery.page = 1
    getList()
}
// 点击清空条件触发
const clearHandle = () => {
    personQuery.search = ''
    personQuery.page = 1
    getList()
}
// 查看图片
const srcList = ref<any>([])
const showViewer = ref(false)// 显示查看器
const showImage = (item:any,index:number) => {
    srcList.value = []
    srcList.value.push(item.addr)
    // 切割数组
    sliders.value.slice(index+1).forEach((item:any) => {
        srcList.value.push(item.addr)
    })
    sliders.value.slice(0,index).forEach((item:any) => {
        srcList.value.push(item.addr)
    })
    showViewer.value = true
}
const closeViewer = () => {
    showViewer.value = false
}
const delItem = async (item: any) => {
    ElMessageBox({
        title: '温馨提示',
        message: h('p', { style: 'font-weight:bold;font-size: 15px;color: #333333;' }, [
            h('span', null, '您确定要删除该数据吗？'),
            h('p', { style: 'font-size: 14px;font-weight:normal;color: rgba(0,0,0,0.65);margin-top:10px;' }, '删除后将无法恢复，确定要继续吗?'),
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: async (action, instance, done) => {
            if (action === 'confirm') {
                const res: any = Number(type.value) === 1 ?await delPhotos({ id: item.id }):Number(type.value) === 2 ?await delXiaobao({ id: item.id }):await delKeyan({ id: item.id })
                if (res.code !== 1) {
                    done()
                    return ElMessage.error(res.msg)
                }
                ElMessage.success(res.msg)
                getList()
                done()
            } else {
                done()
            }
        },
    }).then((action) => {
    })
}
const editRef = ref<any>(null)
const editItem = async (item: any) => {
    editFormVisible.value = true
    nextTick(() => {
        editRef.value.editForm.name = item.name
        editRef.value.editForm.url = item.addr
        editRef.value.editForm.id = item.id
    })
}
const Add= async () => {
    
    editFormVisible.value = true
    nextTick(() => {
        editRef.value.editForm.id = ''
    })
}
// 点击添加角色
const uploaderRef = ref<any>(null)
const signList = ref<any>([])
const finishList = ref<any>([])
const BatchAdd = async () => {
    uploadList.value = []
    totalFiles.value = 0
    validationResults.value = []
    if (uploaderRef.value) {
        uploaderRef.value.$el.querySelector('input').click()
    }
}
const isUploading = ref(false) // 上传状态标记（防止重复触发）
const uploadAvatorAdd = async (options: UploadRequestOptions) => {
    if (totalFiles.value === validationResults.value.length && validationResults.value.some(v => v === false)) {
        return false;
    } else {
        // 仅处理第一个文件的触发（后续文件触发时跳过）
        if (isUploading.value) return
        isUploading.value = true
        loading.value = true
        const formData = new FormData();
        for (const file of uploadList.value) {
            formData.append('files[]', file); // 相同字段名自动生成文件数组
        }
        const res: any = await batchUploadImg(formData)
        if (res.code !== 1){
            return ElMessage.error(res.msg)
        } else {
            let arr:any=[]
            res.data.forEach((item:any) => {
                arr.push({
                    name: item.name.replace(/\.[^.]+$/, ''),
                    url: item.path
                })
            })
            await addPhoto(arr)
        }
        isUploading.value = false
    }
}
const addPhoto = async (file: any) => {
    const res: any = Number(type.value) === 1 ?await addPhotos({ imgs: file }):Number(type.value) === 2 ?await addXiaobao({ imgs: file }):await addKeyan({ imgs: file })
    if (res.code !== 1) return ElMessage.error(res.msg)
    ElMessage.success(res.msg)
    getList()
    loading.value = false
}
// 新增响应式状态管理验证过程
const uploadList = ref<any>([])
const validationResults = ref<boolean[]>([])
const totalFiles = ref(0)
// 上传图片
const beforeAvatarUpload: UploadProps['beforeUpload'] = async (rawFile) => {
    // 重置状态（避免上一次上传残留）
    totalFiles.value++ // 总文件数计数
    // 单个文件验证逻辑
    const typeList = ['image/jpeg', 'image/jpg', 'image/png']
    const isTypeValid = typeList.includes(rawFile.type)
    // 单个文件验证失败处理
    if (!isTypeValid) {
        ElMessage.error(`文件${rawFile.name}类型错误，仅支持jpg/png格式`)
        validationResults.value.push(false)
        return false
    }
    // 单个文件验证通过
    validationResults.value.push(true)
    // 等待所有文件验证完成
    return new Promise((resolve, reject) => {
        const checkAllValid = () => {
            if (validationResults.value.length === totalFiles.value) {
                if (validationResults.value.every(v => v)) {
                    // 全部通过，重置状态并允许上传
                    uploadList.value.push(rawFile)
                    resolve(rawFile)
                } else {

                    reject(new Error('存在文件验证不通过'))
                }
            }
        }
        checkAllValid() // 立即检查（可能已全部验证）
    })
}
const modelCancel = () => {
    editFormVisible.value = false
}
// 点击翻页器的长度
const sizeChange = () => {
    personQuery.page_size = store.pageQuery.page_size
    getList()
}
// 点击翻页器的页码
const CurrentChange = () => {
    personQuery.page = store.pageQuery.page
    getList()
}
onMounted(() => {
    getList()
});
</script>
<style scoped lang="scss">
.user-info-box {
    height: 100%;
}

.xtx-carousel {
    padding: 15px;
    position: relative;
    border-top: 10px solid rgb(247, 247, 247);
    box-sizing: border-box;
    height: calc(100% - 60px);

    &:hover {
        .carousel-btn {
            opacity: 1;
        }
    }

    .listBox {
        margin-top: 15px;
        height: 100%;
        overflow-y: scroll;
        height: calc(100% - 120px);
    }

    .listItem {
        width: 222px;
        height: 190px;
        display: inline-block;
        border-radius: 8px;
        overflow: hidden;
        margin: 0 7px;
        position: relative;
        box-shadow: 0 2px 6px #0000000d;
        margin-bottom: 20px;
        position: relative;

        .img-view-box {
            width: 222px;
            height: 135px;
            position: relative;
            cursor: pointer;
        }

        img {
            width: 222px;
            height: 135px;
            object-fit: cover;
        }

        .teacher-name-box {
            display: inline-block;
            color: #333;
            font-size: 15px;
            width: 100%;
            background-color: #fff;
            padding: 15px;
            box-sizing: border-box;
            text-align: center;
        }

        .model-img-box {
            background: rgba(0, 0, 0, 0.7);
            width: 100%;
            height: 100%;
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            border-radius: 4px;
            z-index: 9;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;

            i {
                color: #fff;
                font-size: 16px;
            }

            .mine-flex-box {
                display: flex;
                justify-content: center;
                align-items: center;
                flex-wrap: wrap;

                .el-icon {
                    transition: all 1s;
                    font-weight: bold;
                    font-size: 20px;
                }

                span {
                    width: 1px;
                    margin: 0 10px;
                    height: 12px;
                    background: rgba(255, 255, 255, 0.9);
                    display: inline-block;
                }

                .el-icon:first-of-type:hover {
                    transform: scale(1.2);
                }

                .el-icon:last-of-type:hover {
                    transform: scale(1.2);
                }
            }
        }
    }
}

:deep(.el-drawer) {
    width: 70% !important;
    min-width: 1060px !important;


    .el-drawer__wrapper {
        overflow: hidden;
    }
}
</style>
